########
# Rocio Titiunik
# 
# plot.pval: A function for plotting balance results in a nice figure.  
########

plot.pval <- function(results, title=NULL, legend,legendx=0.15,legendy=2.2, textsize=0.75, parcex=0.8, at1=-0.35, at2=-0.15, at3=-0.9,xlim1=-0.85) {
	
# set values of different parameters
	xlim = c(xlim1,1); pchset = c(21,22,24,23); pchcolset = c("blue","red","yellow","darkgreen")
	
# set margins and letter size
	par(cex=parcex, mai = c(0.5, 0.35, 1.1, 0.35))
	
# set number of rows 
	ny = nrow(results)
	
# create the empty figure
	if(!is.null(title))  plot(x=NULL,axes=F, xlim=xlim, ylim=c(1,ny),xlab="",ylab="", main=title,family='serif')
	if(is.null(title))   plot(x=NULL,axes=F, xlim=xlim, ylim=c(1,ny),xlab="",ylab="",family='serif')
	
# add the 0, 0.05 and 0.1 vertical lines
	abline(v=c(0,0.05,0.1),lty=c(1,4,4), lwd=c(1,2,2))
	axis(side=1,at=c(0,0.05,0.1,1),tick=TRUE, las=2, cex.axis=0.7)
	
# add labels on top of the three areas of the graph
	axis(side=3,at=at1,labels="Elec. Day\nT-statistic",tick=FALSE, padj=0.5,cex.axis=textsize)
	axis(side=3,at=at2,labels="Prior Weekend\nT-statistic",tick=FALSE, padj=0.5,cex.axis=textsize)
	axis(side=3,at=0.5,labels="P-values",tick=FALSE, padj=0.5,cex.axis=textsize)
	
# Fill the figure with the information which is inside the 'results' matrix
# First, add the p-values as points
	for(i in 4:ncol(results)) points(results[,i],ny:1, pch = pchset[i-4+1], col = pchcolset[i-4+1], bg = pchcolset[i-4+1])
	
# Second, add each variable name and the means for treated and control
	for(i in 1:ny) {
		text(at3,ny-i+1,results[i,1],adj = 0,cex=textsize) # variable name
		text(at1,ny-i+1,results[i,2], cex=textsize)        # treatment mean
		text(at2,ny-i+1,results[i,3], cex=textsize)        # control mean
	}
	
# Add dotted horizontal lines every two variables to make it prettier
	for(i in seq(2,by=2,length.out=floor((ny-1)/2))) abline(h = i+0.5, lty = 3)
	
# Add legend
	if(legend) legend(x=legendx, y=legendy, c("Elec. Day", "Prior Weekend"), pch=pchset, pt.bg = pchcolset, cex=0.8)
}
